<?php

declare(strict_types=1);

namespace App\WorkContact\Logic\Room;

use Hyperf\Di\Annotation\Inject;
use App\WorkContact\Constants\Room\JoinScene as WorkContactRoomJoinScene;
use App\WorkContact\Constants\Room\Status as WorkContactRoomStatus;
use App\WorkContact\Constants\Room\Type as WorkContactRoomType;
use App\WorkContact\Service\WorkContactService;
use App\WorkContact\Service\WorkContactEmployeeService;
use App\WorkContact\Service\WorkContactRoomService;
use App\WorkEmployee\Service\WorkEmployeeService;
use App\WorkRoom\Service\WorkRoomService;
use Base\Constants\ErrorCode;
use Base\Exception\CommonException;

/**
 * 客户群群主-列表.
 *
 * Class OwnerLogic
 */
class OwnerLogic
{
    /**
     * @Inject
     * @var WorkRoomService
     */
    protected $workRoomService;

    /**
     * @Inject
     * @var WorkEmployeeService
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var WorkContactService
     */
    protected $workContactService;

    /**
     * @Inject
     * @var WorkContactRoomService
     */
    protected $workContactRoomService;

    /**
     * @Inject
     * @var WorkContactEmployeeService
     */
    protected $workContactEmployee;

    /**
     * 企业通讯录成员列表.
     * @var array
     */
    protected $employeeList = [];

    /**
     * 企业外部联系人列表.
     * @var array
     */
    protected $contactList = [];

    /**
     * @param array $params 请求参数
     * @return array 响应数组
     */
    public function handle(array $params): array
    {
        ## 处理请求参数
        $params = $this->handleParams($params);
        ## 查询数据
        return $this->getContactRooms($params);
    }

    /**
     * @param int $workRoomId 客户群ID
     * @return array 响应数组
     */
    private function getWorkRoom(int $workRoomId): array
    {
        $data = $this->workRoomService->getWorkRoomById($workRoomId, ['id', 'corp_id', 'owner_id']);

        if (empty($data)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '当前客户群不存在');
        }
        return $data;
    }

    /**
     * @param array $params 请求参数
     * @param array $room 客户群基础信息
     * @return array 响应数组
     */
    private function handleParams( array $params): array
    {
        ## 组织返回数据
        $data = [
            'where' => ['corp_id' => $params['corpId']],
            'options' => [
                'page' => $params['page'],
                'perPage' => $params['perPage'],
                'orderByRaw' => 'id desc',
            ],
            'hadName' => 0,  ## 是否存在成员名称的模糊搜索
        ];
        ## 处理名称
        if (!empty($params['name'])) {
            $data['hadName'] = 1;
            ## 企业通讯录成员模糊匹配
            $this->getEmployees(user()['corp_id'], $params['name']);
            if(!empty($this->employeeList)){
                $data['where']['owner_id'] = array_column($this->employeeList, 'id');
            }
        }

        return $data;
    }

    /**
     * @param int $corpId 企业微信授信ID
     * @param string $name 通讯录成员名称
     */
    private function getEmployees(int $corpId, string $name)
    {
        $data = $this->workEmployeeService->getWorkEmployeesByCorpIdName($corpId, $name, ['id', 'name', 'avatar']);

        $this->employeeList = !empty($data) ? array_column($data, null, 'id') : [];
    }

    /**
     * @param int $corpId 企业微信授信ID
     * @param string $name 通讯录成员名称
     */
    private function getContacts(int $corpId, string $name)
    {
        $data = $this->workContactService->getWorkContactsByCorpIdName($corpId, $name, ['id', 'name', 'avatar']);

        $this->contactList = !empty($data) ? array_column($data, null, 'id') : [];
    }

    /**
     * @param array $params 请求参数
     * @return array 响应数组
     */
    private function getContactRooms(array $params): array
    {
        ## 组织响应数据
        $data = [
            'current' => $params['options']['page'],
            'size' => $params['options']['perPage'],
            'total' => 0,
            'pages' => 0,
            'records' => [],
        ];
        if($params['hadName'] && empty($params['where']['owner_id'])){
            return $data;
        }
        $rooms = $this->workRoomService->getWorkRoomList($params['where'],['owner_id'],$params['options']);
        if(empty($rooms['data'])){
            return $data;
        }
        $ownerId = array_column($rooms['data'],'ownerId');
        $columns = ['id','name','avatar'];
        $employeeList = $this->workEmployeeService->getAllWorkEmployee(['id'=>$ownerId],$columns);
        if(empty($employeeList)){
            return $data;
        }
        $data['total'] = $rooms['total'];
        $data['pages'] = $rooms['last_page'];
        $data['records'] = $employeeList;
        return $data;
    }
}
